import {createRouter, createWebHistory} from "vue-router";
import {ElMessage} from "element-plus";

const routes = [
    {path: '/login', component: () => import('../components/Login.vue')},
    {path: '/blogin', component: () => import('../components/BackgroundLogin.vue')},
    {
        path: '/home', component: () => import('../components/Home.vue'),
        meta: { requiresAuth: true, role: 'admin' }, // 仅管理员可访问
        children: [
            {path: '', redirect: '/dashboard'},
            {path: '/userList', component: () => import('../components/UserList.vue')},
            {path: '/dashboard', component: () => import('../pages1/Dashboard.vue')},
            {path: '/userDetail', component: () => import('../components/UserDetail.vue')},
            {path: '/merchantList', component: () => import('../components/merchantList.vue')},
            {path: '/merchantDetail', component: () => import('../components/merchantDetail.vue')},
            {path: '/goodsList', component: () => import('../components/goodsList.vue')},
            {path: '/goodsUpdate', component: () => import('../components/goodsUpdate.vue')},
            {path: '/groupBuyList', component: () => import('../components/groupBuyList.vue')},
            {path: '/groupBuyList', component: () => import('../components/groupBuyList.vue')},
            {path: '/goodsAdd', component: () => import('../components/goodsAdd.vue')},
            {path: '/groupBuyAdd', component: () => import('../components/groupBuyAdd.vue')},
            {path: '/groupBuyDetail', component: () => import('../components/groupBuyDetail.vue')},
            {path: '/system', component: () => import('../components/System.vue')},
            {path: '/orderList', component: () => import('../components/orderList.vue')},
        ]
    },
    {path: "/merchantHome",component: ()=>import ("../components/merchantHome.vue"),

        meta: { requiresAuth: true, role: 'merchant' }, // 仅商家可访问
        children: [
            {path: '', redirect: '/merchantInfo'},{
        path: "/completeInfo",component: () => import("../components/completeInfo.vue")
        },{
        path: "/merchantInfo",component: () => import("../components/merchantInfo.vue")
        },{
        path: "/merchantGoodsList",component: () => import("../components/merchantGoodsList.vue")
        },{
        path: "/merchantGoodsUpdate",component: () => import("../components/merchantGoodsUpdate.vue")
        },{
        path: "/merchantGoodsAdd",component: () => import("../components/merchantGoodsAdd.vue")
        },{
        path: "/merchantGroupBuyList",component: () => import("../components/merchantGroupBuyList.vue")
        },{
        path: "/merchantGroupBuyDetail",component: () => import("../components/merchantGroupBuyDetail.vue")
        },{
        path: "/merchantGroupBuyUpdate",component: () => import("../components/merchantGroupBuyUpdate.vue")
        },{
        path: "/merchantGroupBuyAdd",component: () => import("../components/merchantGroupBuyAdd.vue")
        }]
    },
    {path: '/registered', component: () => import('../components/Registered.vue')},
    {path: '/', redirect: '/blogin'},
    {
        path: '/index', component: () => import('../components/Index.vue'),

        children: [
            {path: '/myDetail', component: () => import('../pages1/myDetail.vue')},
            {path: '/web', component: () => import('../components/WebSocket.vue')},
        ]
    },
    {path: '/profile', component: () => import('../pages1/Profile.vue')},

    {path: '/certification', component: () => import('../pages1/Certification.vue')},
    {path: '/wallet', component: () => import('../pages1/Wallet.vue')},
    {path: '/signIn', component: () => import('../pages1/SignIn.vue')},
    {path: '/chatai', component: () => import('../pages1/AI.vue')},
    {path: '/coupon/:points',props: true, component: () => import('../pages1/Coupon.vue')},
]
const router = createRouter({
    history: createWebHistory(),
    routes
})
// 增加拦截
router.beforeEach((to, from, next) => {
    const token = sessionStorage.getItem("token");
    const role = sessionStorage.getItem("role");

    // 1. 处理登录页（/blogin）：已登录跳对应首页，未登录放行
    if (to.path === "/blogin") {
        if (token) {
            // 已登录：根据角色跳对应首页（仅跳一次，不重复触发）
            if (role === "admin") {
                next("/home"); // 管理员跳管理员首页
            } else if (role === "merchant") {
                next("/merchantHome"); // 商家跳商家首页
            } else {
                // 角色异常：清除存储，留在登录页
                sessionStorage.clear();
                ElMessage.error("角色信息异常，请重新登录");
                next(); // 放行到登录页（避免重复跳转）
            }
        } else {
            // 未登录：直接放行到登录页（正确路径是 /blogin，之前少了 /）
            next();
        }
        // 关键：处理完登录页逻辑后，直接 return 避免后续代码执行
        return;
    }

    // 2. 处理需要登录权限的路由（meta.requiresAuth: true）
    if (to.meta.requiresAuth) {
        // 2.1 未登录：拦截到登录页
        if (!token || token === "") {
            ElMessage.warning("请先登录");
            next("/blogin");
            return; // 拦截后直接 return
        }

        // 2.2 已登录：验证角色权限
        const targetRole = to.meta.role; // 路由要求的角色（如 admin/merchant）
        if (role === targetRole) {
            // 角色匹配：直接放行（之前错误跳首页，导致无法访问目标路由）
            next();
        } else {
            // 角色不匹配：拦截并跳对应角色首页
            ElMessage.error(`您没有访问${targetRole === 'admin' ? '管理员' : '商家'}页面的权限`);
            if (role === "admin") {
                next("/home");
            } else if (role === "merchant") {
                next("/merchantHome");
            } else {
                // 角色异常：退出登录
                sessionStorage.clear();
                next("/blogin");
            }
        }
        return; // 处理完权限路由后 return
    }

    // 3. 不需要登录的路由（漏配 meta.requiresAuth 的路由）：默认拦截到登录页
    // ElMessage.warning("该页面需要登录后访问");
    next();
});
export default router